package org.springframework.validation.mvc;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.mvc.annotations.SuccessView;
import org.springframework.validation.util.RequestUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class AnnotatedDefaultViewSettingHandlerInterceptor extends HandlerInterceptorAdapter {
	
	@Autowired
	private ControllerMethodNegotiator controllerMethodNegotiator;
	
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
		SuccessView successView = (SuccessView)
			controllerMethodNegotiator.getAnnotationFromControllerMethod(
				handler, request, SuccessView.class);
		
		if (successView == null) {
			return;
		}
				
		String[] candidateViewNames = successView.value();
		String[] controllerPaths = RequestUtils.getControllerRequestPaths(handler);
		String viewName = RequestUtils.findMatchingRestPath(candidateViewNames, controllerPaths, request);
		
		if (viewName == null) {
			return;
		}
		
		viewName = RequestUtils.replaceRestPathVariables(viewName, modelAndView.getModel(),  request);
		modelAndView.setViewName(viewName);
	}
}
